// map.js
import qqmapsdk from '../../../utils/qqmap'
Page({
  data: {
    latitude: 40.066122,
    longitude: 116.353771,
    markers: [{
        id: 1,
        latitude: 40.066031,
        longitude: 116.353771,
        width: 24,
        height: 30,
      },
      {
        id: 2,
        latitude: 40.079537,
        longitude: 116.340202,
        iconPath: '/static/images/marker.png',
        width: 40,
        height: 40,
      },
    ],
    dialogVisible: false
  },
  onLoad({
    id
  }) {
    this.getRepairDetail(id)
  },
  async getRepairDetail(id) {
    if (!id) return
    const {
      code,
      data: repairDetail
    } = await wx.http.get('/repair/' + id)
    // 校验接口调用结果
    if (code !== 10000) return wx.utils.toast('获取报修详情失败')
    // 渲染报修详情
    this.setData({
      ...repairDetail
    }, () => {
      // 只有在上门中才进行线路规划
      if (this.data.status === 2) {
        this.getPolyLine()
      }
    })
  },
  getPolyLine() {
    qqmapsdk.direction({
      mode: 'bicycling', // driving bicycling walking
      from: '40.079537,116.340202',
      to: '40.066031,116.353771',
      success: (res) => {
        var ret = res
        var coors = ret.result.routes[0].polyline,
          pl = []
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({
            latitude: coors[i],
            longitude: coors[i + 1]
          })
        }
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        this.setData({
          polyline: [{
            points: pl, // 经纬度数组
            color: '#FF0000DD', // 线的颜色
            colorList: ['#ff0000', '#00ff00', '#0000ff'],
            width: 4, // 线的宽度
          }, ],
        })
      },
      fail: (error) => {
        console.error(error)
      },
    })
  },
  showDialog() {
    this.setData({
      dialogVisible: true
    })
  },
  dialogClose(e) {
    e.detail === 'confirm' && this.cancelRepair()
  },
  async cancelRepair() {
    const {
      code
    } = await wx.http.put(`/cancel/repaire/${this.data.id}`)
    if (code !== 10000) return wx.utils.toast('取消报修失败')
    wx.navigateBack()
  },
  editRepair() {
    wx.navigateTo({
      url: `/repair_pkg/pages/form/index?id=${this.data.id}`,
    })
  }
})